package com.pro01.carcontrol.controller;

import com.pro01.carcontrol.config.CarConfig;
import com.pro01.carcontrol.encode.CarDirection;
import com.pro01.carcontrol.encode.CarEncode;
import com.pro01.carcontrol.tcp.TCPClient;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

@ServerEndpoint("/ws/car")
@Component
public class CarWebSocket {

    private static CarConfig carConfig;
    private static TCPClient tcpClient;  // ✅ 全局复用

    @Autowired
    public void setCarConfig(CarConfig config) {
        carConfig = config;
    }

//    @OnOpen
//    public void onOpen(Session session) {
//        System.out.println("🚗 WebSocket连接建立：" + session.getId());
//
//        // ① 初始化小车
//        try {
//            String initUrl = "http://" + carConfig.getIp() + ":" + carConfig.getInitPort() + "/init";
//            HttpURLConnection conn = (HttpURLConnection) new URL(initUrl).openConnection();
//            conn.setRequestMethod("GET");
//            conn.setConnectTimeout(3000);
//            int code = conn.getResponseCode();
//            if (code == 200) {
//                System.out.println("✅ 成功初始化小车服务端！");
//                session.getBasicRemote().sendText("✅ 初始化成功！");
//            } else {
//                System.err.println("❌ 初始化失败，状态码: " + code);
//                session.getBasicRemote().sendText("❌ 初始化失败，状态码: " + code);
//            }
//        } catch (IOException e) {
//            System.err.println("❌ 无法连接小车初始化接口：" + e.getMessage());
//            try {
//                session.getBasicRemote().sendText("❌ 无法连接初始化接口: " + e.getMessage());
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//
//        // ② 初始化 TCP 客户端（如果尚未连接）
//        if (tcpClient == null) {
//            tcpClient = new TCPClient(carConfig.getIp(), carConfig.getTcpPort());
//        }
//    }
private static boolean inited = false;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("🚗 WebSocket连接建立：" + session.getId());

        if (!inited) {
            try {
                String initUrl = "http://" + carConfig.getIp() + ":" + carConfig.getInitPort() + "/init";
                HttpURLConnection conn = (HttpURLConnection) new URL(initUrl).openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(3000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    inited = true; // ✅ 只初始化一次
                    System.out.println("✅ 成功初始化小车服务端！");
                    session.getBasicRemote().sendText("初始化成功");
                } else {
                    System.err.println("❌ 初始化失败，状态码: " + code);
                    session.getBasicRemote().sendText("❌ 初始化失败，状态码: " + code);
                }
            } catch (IOException e) {
                System.err.println("❌ 无法连接小车初始化接口：" + e.getMessage());
                try {
                    session.getBasicRemote().sendText("❌ 无法连接初始化接口: " + e.getMessage());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            System.out.println("⚠️ 已初始化，无需重复请求 /init");
            try {
                session.getBasicRemote().sendText("初始化成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 初始化 TCPClient
        if (tcpClient == null) {
            tcpClient = new TCPClient(carConfig.getIp(), carConfig.getTcpPort());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("📥 收到控制指令: " + message);
        try {
            CarDirection dir = CarDirection.valueOf(message);
            String encoded = CarEncode.buttonCarEncode(dir);

            if (tcpClient != null) {
                tcpClient.sendCommand(encoded);
                session.getBasicRemote().sendText("✅ 已发送指令：" + encoded);
            } else {
                session.getBasicRemote().sendText("❌ TCP连接尚未建立！");
            }
        } catch (IllegalArgumentException e) {
            System.err.println("❌ 无效的控制指令: " + message);
            try {
                session.getBasicRemote().sendText("❌ 指令不合法: " + message);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("❌ 指令发送失败: " + e.getMessage());
            try {
                session.getBasicRemote().sendText("❌ 指令发送失败: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("🔌 WebSocket连接关闭：" + session.getId());
        if (tcpClient != null) {
            tcpClient.close();  // ✅ 释放资源
            tcpClient = null;
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("⚠️ WebSocket连接出错：" + error.getMessage());
    }
}